﻿using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Linq;
using System.Text;

namespace Fast.Swagger
{
    [SkipScan]
    public class EnumSchemaFilter : ISchemaFilter
    {
        /// <summary>
        /// 实现过滤器方法
        /// </summary>
        /// <param name="model"></param>
        /// <param name="context"></param>
        public void Apply(OpenApiSchema model, SchemaFilterContext context)
        {
            var type = context.Type;

            // 排除其他程序集的枚举
            if (type.IsEnum && App.Assemblies.Contains(type.Assembly))
            {
                var stringBuilder = new StringBuilder();

                Enum.GetNames(context.Type)
                    .ToList()
                    .ForEach(name =>
                    {
                        var enumObj = Enum.Parse(context.Type, name);
                        stringBuilder.Append($"{name}({((Enum)enumObj).GetDescription()}) = {Convert.ToInt64(enumObj)}<br />");
                    });
                model.Description = stringBuilder.ToString();
            }
        }
    }
}